package com.android.act.setting;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.android.R;
import com.android.common.Action;
import com.android.common.filetools.FileUtils;
import com.android.common.filetools.HttpDownloader;
import com.android.model.UpdataDao;

public class UpdateActivity extends Activity {
	Action acion;
	private Button menuBtn;
	private TextView topbar_title;
//	private DataParserTool dataParser = null;
	private UpdataDao updata = null; 
	private String PastVersion;// 旧版本号
	private String NowVersion;// 新版本号
	public ProgressDialog pBar; // 进度条
	private HttpDownloader downloader;
	private String apkPath;
	private String  tempName = "/temp.apk";
	private Dialog dialog;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting_update_main);
		acion = new Action(UpdateActivity.this);
		downloader = new HttpDownloader();
		initView();

	}
	private void initView() { 
		topbar_title = (TextView) findViewById(R.id.titlebar_name);
		topbar_title.setText("版本更新");
		Button updataBut = (Button) findViewById(R.id.setting_updatabut);
		updataBut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				dataParser = new DataParserTool(UpdateActivity.this);
//				updata = dataParser.getUpdataInfo("1", "iphone","");
				String NowVersion = updata.getVersion();
					
					// 装载获取当前的版本号
					load();
					
					//当有最新版本的时候
					Log.d("update", "pastVersion:"+PastVersion+"&&Nowversion:"+NowVersion);
					if(PastVersion != null&&!(PastVersion.equals(NowVersion)))
					{	
						
						   dialog = new AlertDialog.Builder(UpdateActivity.this).setTitle("系统更新")       
				         .setMessage("发现新版本，请更新！")// 设置内容       
				         .setPositiveButton("确定",// 设置确定按钮       
				                     new DialogInterface.OnClickListener() {       
				                         public void onClick(DialogInterface dialog,       
				                                 int which) {       
						                            pBar = new ProgressDialog(UpdateActivity.this);       
						                            pBar.setTitle("正在下载");       
						                            pBar.setMessage("请稍候...");       
						                            pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
						                            pBar.show();
						                            try {
														getDataSource();
													} catch (Exception e) {
														// TODO Auto-generated catch block
														e.printStackTrace();
													}
				                         }       
				                    }).setNegativeButton("取消",         
				                 new DialogInterface.OnClickListener() {       
				                    public void onClick(DialogInterface dialog,       
				                             int whichButton) {       
				                         // 点击"取消"按钮之后退出程序         
				                     }       
				                 }).create();// 创建       
						 // 显示对话框       
						 dialog.show();       
					}
					//
					else{
						acion.showShortToast( "当前为最新版本");					 
					}
			}
		

		});

	}
	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
//			parentActivity.getScrollView().setMenuBtn(menuBtn);
//			parentActivity.getScrollView().clickMenuBtn();
		}
	};
	/* 取得远程文件 */
	private void getDataSource() throws Exception {
		
		apkPath = downloader.getPath() + "/apk";
		FileUtils.delFile(apkPath+tempName);
		int result = downloader.downFileFromRaw(UpdateActivity.this, apkPath, tempName,R.raw.abc);

		if (result==0||result==1) {
			dialog.dismiss();
			acion.showShortToast( "下载成功");	 
		} 
		

//
			/* 打开文件进行安装 */
		
		Log.v("打开文件", apkPath+tempName);
			openFile(new File(apkPath+tempName));
	
	}

	/* 在手机上打开文件的method */
	private void openFile(File f) {
		pBar.cancel();
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);

		/* 调用getMIMEType()来取得MimeType */
		String type = getMIMEType(f);
		/* 设定intent的file与MimeType */
		intent.setDataAndType(Uri.fromFile(f), type);
		startActivity(intent);
	}

	/* 判断文件MimeType的method */
	private String getMIMEType(File f) {
		String type = "";
		String fName = f.getName();
		Log.v("fName", fName);
		/* 取得扩展名 */
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();

		/* 按扩展名的类型决定MimeType */
	if (end.equals("apk")) {
			/* android.permission.INSTALL_PACKAGES */
			type = "application/vnd.android.package-archive";
		} else {
			type = "*";
		}
		return type;
	}

	boolean load() {
		/**  
		 * 返回当前程序版本名  
		 */  
		    try {   
		        // ---get the package info---   
		        PackageManager pm = this.getPackageManager();   
		        PackageInfo pi = pm.getPackageInfo(this.getPackageName(), 0);   
		        PastVersion = String.valueOf(pi.versionCode);
		        Log.v("PastVersion", PastVersion);
		        return true;
		    } catch (Exception e) { 
		        return false;
		    }   
	}


}